package com.hualan.servlet.fileUpServlet;


import com.alibaba.fastjson.JSON;
import com.hualan.bean.JsonResult;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@WebServlet("/goods/fileup")
@MultipartConfig(
		fileSizeThreshold = 0,
		maxFileSize = 1024 * 1024 * 10,
		maxRequestSize = 1024 * 1024 * 15
)
public class FileUpServlet extends HttpServlet {
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Part file = req.getPart("file");
		String fileName = req.getParameter("fileName");
		// 获取文件名
		String submittedFileName = file.getSubmittedFileName();
		// 获取文件后缀
		String suffix = submittedFileName.substring(submittedFileName.length() - 4);
		// 获取文件内容
		InputStream inputStream = file.getInputStream();
		// 获取项目真实路径（在服务器上部署的地址）
		String realPath = req.getServletContext().getRealPath("/");
		File dir = new File(realPath+"/goodsAvatar");
		// 如果目录不存在则创建
		if (!dir.exists()){
			dir.mkdir();
		}
		// 创建文件
		File file1 = new File(dir,fileName);
		if (!file1.exists()){
			file1.createNewFile();
		}
		// 提交
		Files.copy(inputStream, file1.toPath(), StandardCopyOption.REPLACE_EXISTING);
		req.getSession().setAttribute("filePath",file1.toPath().toString());
		resp.getWriter().write(JSON.toJSONString(JsonResult.success(200,"上传成功")));
	}
}
